package com.liuya.shiro;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.liuya.common.SecurityUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @Author 刘亚
 * @Date 2016/12/7
 */
public class RSAService {
    private static final String PRIVATE_KEY = "privateKey";
    private static final String PUBLIC_KEY = "publicKey";

    public static RSAPublicKey generateKey(HttpServletRequest request) {
        Assert.notNull(request);
        KeyPair pair = SecurityUtil.generateKeyPair();
        RSAPublicKey key = (RSAPublicKey) pair.getPublic();
        RSAPrivateKey key1 = (RSAPrivateKey) pair.getPrivate();
        HttpSession session = request.getSession();
        session.setAttribute(PRIVATE_KEY, key1);
        session.setAttribute(PUBLIC_KEY, key);
        return key;
    }

    public static void removePrivateKey(HttpServletRequest request) {
        Assert.notNull(request);
        HttpSession session = request.getSession();
        session.removeAttribute(PRIVATE_KEY);
    }

    public static String encryptRsa(String value, HttpServletRequest request) {
        Assert.notNull(request);
        if (value != null) {
            HttpSession session = request.getSession();
            RSAPublicKey key = (RSAPublicKey) session.getAttribute(PUBLIC_KEY);
            if (key != null && StringUtils.isNotEmpty(value))
                return SecurityUtil.encryptRsa(key, value);
        }
        return null;
    }

    public static String decryptRsa(String name, HttpServletRequest request) {
        Assert.notNull(request);
        if (name != null) {
            HttpSession session = request.getSession();
            RSAPrivateKey key = (RSAPrivateKey) session.getAttribute(PRIVATE_KEY);
            String str = request.getParameter(name);
            if (key != null && StringUtils.isNotEmpty(str))
                return SecurityUtil.decryptRsa(key, str);
        }
        return null;
    }
}
